package org.example.listener;

import com.rabbitmq.client.Channel;
import org.example.bean.ProductEsBean;
import org.example.common.MqConstants;
import org.example.dao.ProductEsDao;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class ProductListener {
    @Autowired
    private ProductEsDao productEsDao;
    private AtomicInteger reTryCount = new AtomicInteger(0);

    @RabbitListener(queues = MqConstants.HOTEL_INSERT_QUEUE)
    public void listenProductAdd(Long id, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag){
        System.out.println("id="+id);

        ProductEsBean productEsBean = new ProductEsBean();
        productEsBean.setId(id);
        productEsBean.setTitle("小米手机"+id);
        productEsBean.setCategory("手机"+id);
        productEsBean.setPrice(3199.0);
        productEsBean.setImages("http://www.atguigu/xm.jpg");
        productEsDao.save(productEsBean);

        try {
            channel.basicAck(tag, false);  //作用:消息确认接收，参数2是否批量，true表示一次性ack所有小于tag的消息
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /*@RabbitListener(queues = MqConstants.HOTEL_INSERT_QUEUE)
    public void receiveMsg(Object args, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, Long id) {
        // 下面是手动消息应答
        try {
            int i = 1/0;
            channel.basicAck(tag, false);  //作用:消息确认接收，参数2是否批量，true表示一次性ack所有小于tag的消息
        } catch (Exception e) {
            reTryCount.getAndIncrement();
            throw new RuntimeException(e);
        } finally {
            //已达最大次数 人工维护这些数据 落表或者死信队列或者新的queue
            if(reTryCount.get() >= 3){
                System.out.println("已达最大次数");
            }
        }
        // channel.basicNack(tag, false, true) 作用:拒绝或重新入队列, 参数2是否批量同上，参数3被拒绝的是否重新入队列
        // channel.basicReject(tag, false) 作用:拒绝或重新入队列(只能一次拒绝一条消息)，参数2被拒绝的是否重新入队列
    }*/
}
